import React,{ useLayoutEffect } from "react";
import { useSelector,useDispatch } from "react-redux";
import { formatDistanceToNow, parseISO } from "date-fns";
import classnames from "classnames";

import { selectAllUsers } from "../users/usersSlice";

import { 
  selectAllNotifications,
  allNotificationsRead, 
  useGetNotificationsQuery,
  selectMetadataEntities
} from "./notificationsSlice";


const NotificationsList = () => {
  const dispatch = useDispatch();
  const { data: notifications = [] } = useGetNotificationsQuery()
  const notificationsMetadata = useSelector(selectMetadataEntities)

  //const notifications = useSelector(selectAllNotifications);
  //console.log('notifications',notifications)
  const users = useSelector(selectAllUsers);

  const renderedNotifications = notifications.map((notification) => {
    const date = parseISO(notification.date);
    const timeAgo = formatDistanceToNow(date);
    const user = users.find((user) => user.id === notification.user) || {
      name: "Unknown User",
    };

    const metadata = notificationsMetadata[notification.id]

    const notificationClassname = classnames('notification', {
      // highlight-next-line
      new: metadata.isNew,
    })

    // const notificationClassname = classnames("notification", {
    //   new: notification.isNew,
    // });
    return (
      <div key={notification.id} >
        <div>
          <b>{user.name}</b> {notification.message}
        </div>
        <div title={notification.date}>
          <i>{timeAgo} ago</i>
        </div>
        <div>read: {notification.read ? '已读': '未读'}</div>
      </div>
    );
  });


  useLayoutEffect(() => {
    console.log('请求次数')
    dispatch(allNotificationsRead());
  });

  return (
    <section className="notificationsList">
      <h2>Notifications</h2>
      {renderedNotifications}
    </section>
  );
};

export default NotificationsList;